package com.awesome.aidldemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import androidx.annotation.Nullable;

import com.awesome.common.util.log.ShowLogUtil;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2021/6/16 7:34 上午
 * Description: 单独进程的服务
 */
public class AidlService extends Service {
    private boolean mFlag;
    private OnDownloadListener mOnDownloadListener;
    private DownloadManager mDownloadManager = new DownloadManager(AidlService.this) ;


    @Override
    public void onCreate() {
        super.onCreate();
        ShowLogUtil.info("远程服务 onCreate");
        mFlag = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ShowLogUtil.info("远程服务 onStartCommand");
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 1; i < 100; i++) {
//                    try {
//                        Thread.sleep(2000);
//                        mProgress += 1;
//                        if (i != mProgress) i = mProgress;
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    ShowLogUtil.info("远程正在执行 i=" + i);
//                    // 销毁服务时，结束线程中的循环
//                    if (!mFlag) break;
//                }
//
//            }
//        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        ShowLogUtil.info("远程绑定 onBind");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    mDownloadManager.download();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return new IMyBinder.Stub() {

            @Override
            public IDownloadManager getDownloadManager() throws RemoteException {
                return mDownloadManager;
            }

            @Override
            public void registerDownloadListener(OnDownloadListener onDownloadListener) throws RemoteException {
                mOnDownloadListener = onDownloadListener;
            }
        };
    }

    @Override
    public boolean onUnbind(Intent intent) {
        ShowLogUtil.info("远程解绑 onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ShowLogUtil.info("远程销毁 onDestroy");
        mFlag = false;
    }

    public OnDownloadListener getOnDownloadListener() {
        return mOnDownloadListener;
    }
}